package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.ObjectArrays;
import com.sky.WebSocket.WebSocketServer;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.exception.UserNotLoginException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrdersService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description TODO
 * @Author itheima
 * @Date 2023-07-20 18:39
 */
@Service
@Slf4j
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    private OrdersDetailMapper ordersDetailMapper;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Value("${sky.shop.address}")
    private  String mindaddress ;
    @Value("${sky.baidu.Ak}")
    private  String ak ;

    /**
     * 用户下单接口
     *
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //将订单表的实体类完善
        Orders orders = new Orders();
        //将DTO的数据拷贝给实体类
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        //完善订单数据(唯一,uuid.这里要求数据长度不超过32位,微信支付的要求)
        //uuid默认带有"-"是36位去掉就是32
        String number = UUID.randomUUID().toString().replace("-", "");
        orders.setNumber(number);
        //订单状态
        orders.setStatus(Orders.PENDING_PAYMENT);
        //用户id
        Long userid = BaseContext.getCurrentId();
        orders.setUserId(userid);
        //下单时间
        orders.setOrderTime(LocalDateTime.now());
        //支付状态
        orders.setPayStatus(Orders.UN_PAID);
        //查询地址表的数据
        AddressBook byId = addressBookMapper.getById(orders.getAddressBookId());
        if (byId == null) {
            //地址为空
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //手机号
        String phone = byId.getPhone();
        orders.setPhone(phone);
        //地址
        String address = byId.getProvinceName() + byId.getCityName() + byId.getDistrictName() + byId.getDetail();
        //验证是否超出配送范围
        getlocation(address);
        orders.setAddress(address);
        //收货人
        orders.setConsignee(byId.getConsignee());
        //根据用户id查询用户
        User user = userMapper.getByUserId(userid);
        if (user == null) {
            //判断是否有数据
            throw new UserNotLoginException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        //用户名
        orders.setUserName(user.getName());
        //将订单数据插入订单表
        ordersMapper.insert(orders);

        //查询购物车
        List<ShoppingCart> byUserId = shoppingCartMapper.findByUserId(userid);
        //
        List<OrderDetail> ordersd = new ArrayList<>();
        if (byUserId == null && byUserId.size() == 0) {
            //购物车为空
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        for (ShoppingCart shoppingCart : byUserId) {
            //创建订单明细表的实体类
            OrderDetail orderDetail = new OrderDetail();
            //订单表
            orderDetail.setOrderId(orders.getId());
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            ordersd.add(orderDetail);
        }
        //将明细表插入数据库
        ordersDetailMapper.insert(ordersd);
        //返还数据
        OrderSubmitVO build = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderAmount(orders.getAmount())
                .orderNumber(number)
                .orderTime(orders.getOrderTime()).build();
        //清空购物车
        shoppingCartMapper.clean(userid);
        return build;

    }
    public  void  getlocation(String daddress ){
        //获取百度地理编码接口地址
        String url="https://api.map.baidu.com/geocoding/v3/?address";
        //创建集合存储
      Map <String ,String> map =new HashMap<>();
      //商家地址
      map.put("address",mindaddress);
      //商家申请注册的key
      map.put("ak",ak);
      //返回的数据格式
      map.put("output","josn");
      //使用httpClient技术像百度发送请求
        String s = HttpClientUtil.doGet(url, map);
        //转换成JSONObject格式
        JSONObject jsonObject = JSONObject.parseObject(s);
        // 根据返回的数据类型来使用具体方法如getJSONObject("result") 因为返回的数据中result是Object格式 所以用getJSONObject
        //方法,lng需要String
        JSONObject jsonObject1 = jsonObject.getJSONObject("result").getJSONObject("location");
        //经度
        String lng = jsonObject1.getString("lng");
        //纬度
        String lat = jsonObject1.getString("lat");
        //商家地址编码
        String location=lat+","+lng;
//用户地址
        map.put("address",daddress);
        //获取用户地理编码
        String s1 = HttpClientUtil.doGet(url, map);
         jsonObject = JSONObject.parseObject(s1);
         jsonObject1 = jsonObject.getJSONObject("result").getJSONObject("location");
         lng = jsonObject1.getString("lng");
         lat = jsonObject1.getString("lat");
        String userlocation=lat+","+lng;
        //路线规划接口地址
        String url2 ="https://api.map.baidu.com/directionlite/v1/driving";
        Map<String,String> map1=new HashMap<>();
        map1.put("origin",location);//商家地理编码
        map1.put("destination",userlocation);//用户地理编码
        map1.put("ak",ak);
        String reten = HttpClientUtil.doGet(url2, map);
        JSONObject jsonObject2 = JSONObject.parseObject(reten);
        JSONObject result = jsonObject2.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        //距离
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");

        if(distance > 5000){
            //配送距离超过5000米
            throw new OrderBusinessException("超出配送范围");
        }
    }

    @Autowired
    private WeChatPayUtil weChatPayUtil;

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getByUserId(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    @Override
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = ordersMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();
        Map map = new HashMap();
        map.put("type",1);
        map.put("orderId",orders.getId());
        map.put("content","消息内容为"+outTradeNo);
        webSocketServer.sendToAllClient(JSON.toJSONString(map));

        ordersMapper.update(orders);
    }

    /**
     * 根据id查询详情
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO findByorderId(Long id) {
        Orders order = ordersMapper.findByorderId(id);

        List<OrderDetail> orderDetail = ordersDetailMapper.findByorderDetailId(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(order, orderVO);
        orderVO.setOrderDetailList(orderDetail);
        return orderVO;
    }

    /**
     * 查询历史订单
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult page(OrdersPageQueryDTO ordersPageQueryDTO) {
        //分页
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        //将用户id放入
        Long useid = BaseContext.getCurrentId();
        ordersPageQueryDTO.setUserId(useid);
        //查询数据
        Page<Orders> page = ordersMapper.page(ordersPageQueryDTO);
        //创建一个空集合存存数据
        List<OrderVO> list = new ArrayList<>();
        //判断取出的数据是否为null
        if (page != null && page.size() > 0) {
            //遍历集合page
            for (Orders orderVO : page) {
                //拿出订单表id
                Long orderid = orderVO.getId();
                //根据订单id查询用户明细表
                List<OrderDetail> byorderDetailId = ordersDetailMapper.findByorderDetailId(orderid);
                //创建用户实体类VO存数据
                OrderVO orderVOs = new OrderVO();
                //拷贝数据
                BeanUtils.copyProperties(orderVO, orderVOs);
                //将明细表的集合放入实体类VO
                orderVOs.setOrderDetailList(byorderDetailId);
                list.add(orderVOs);
            }
        }
        return new PageResult(page.getTotal(), list);
    }

    /**
     * 根据id再来一单
     *
     * @param id
     */
    @Override
    public void repetitionid(Long id) {
        //首先根据id查出订单明细表
        //然后遍历订单明细表 完善购物车表的数据
        //将数据插入购物车表
        List<OrderDetail> byorderDetailId = ordersDetailMapper.findByorderDetailId(id);
                if (byorderDetailId==null&&byorderDetailId.size()==0){
                    throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
                }
        for (OrderDetail orderDetail : byorderDetailId) {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartMapper.add(shoppingCart);
        }
    }

    /**
     * 取消订单
     *
     * @param orderss
     */
    @Override
    public void  updateid(Orders orderss) throws Exception {
        //现根据id取出订单表的数据
        //然后修改订单表的status的数据
        //插入修改过后的订单表数据

        Orders orders = ordersMapper.findByorderId(orderss.getId());
        if (orders==null||!orders.getStatus().equals(Orders.TO_BE_CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        if (orders.getStatus().equals(Orders.PAID)){
            String refund = weChatPayUtil.refund(orders.getNumber(),
                    orders.getNumber(),
                    orders.getAmount(),
                    orders.getAmount());
            log.info("退款:{}", refund);
            orders.setPayStatus(Orders.REFUND);
        }
        Orders order = Orders.builder()
                .cancelTime(LocalDateTime.now())
                .id(orders.getId())
                        .status(Orders.CANCELLED)
                        .build();
        if (orders.getRejectionReason()==null){
            order.setCancelReason("用户取消");
        }else {  order.setRejectionReason(orderss.getRejectionReason());}

        ordersMapper.update(order);
    }

    /**
     * 订单搜索
     *
     * @param ordersPageQueryDTOP
     * @return
     */
    @Override
    public PageResult pageadmin(OrdersPageQueryDTO ordersPageQueryDTOP) {
        //使用工具类 将参数 页数 每页显示数据的个数传进去通过计算
        PageHelper.startPage(ordersPageQueryDTOP.getPage(), ordersPageQueryDTOP.getPageSize());
        //查询
        Page<Orders> page = ordersMapper.page(ordersPageQueryDTOP);
        //拿到所有的存储Orders实体类集合的数据
        List<Orders> result = page.getResult();
        //创建一个存储OrdersVO实体类的集合
        List<OrderVO> orderVOlist = new ArrayList<>();
        //将数据做一个安全的判空处理
        if (result == null && result.size() == 0) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //遍历集合
        for (Orders orders : result) {
            //创建一个实体类
            OrderVO orderVO = new OrderVO();
            //根据订单id取出订单明细表的数据
            List<OrderDetail> byorderDetailId = ordersDetailMapper.findByorderDetailId(orders.getId());
            //拷贝
            BeanUtils.copyProperties(orders, orderVO);
            //通过stream流 将byorderDetailId中存储的自定义类转换成字符串并以集合的方式返回
            List<String> collect = byorderDetailId.stream().map(orderDetail ->
                            orderDetail.getName() + "*" + orderDetail.getNumber())
                    .collect(Collectors.toList());
            //通过Strong的api Join 传递一个任意字符 和存储String类型的集合,返回一个以 任意字符为间隔的集合中的数据做拼接而成的字符串
            String join = String.join(" ", collect);
            //将字符串给到orderVO实体类中的变量
            orderVO.setOrderDishes(join);
            //将实体类存入集合
            orderVOlist.add(orderVO);

        }
        //返回
        return new PageResult(page.getTotal(), orderVOlist);
    }

    /**
     * 个状态数量的统计
     *
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {

        // 根据状态，分别查询出待接单、待派送、派送中的订单数量
        Integer toBeConfirmed = ordersMapper.countStatus(Orders.TO_BE_CONFIRMED);
        Integer confirmed = ordersMapper.countStatus(Orders.CONFIRMED);
        Integer deliveryInProgress = ordersMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);

        // 将查询出的数据封装到orderStatisticsVO中响应
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }

    /**
     * 接单
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
    ordersConfirmDTO.setStatus(Orders.CONFIRMED);
    Orders orders =  new Orders();
    BeanUtils.copyProperties(ordersConfirmDTO,orders);
          ordersMapper.update(orders);
    }

    /**
     * 派送订单
     * @param id
     */
    @Override
    public void deliveryId(Long id) {
        Orders byorderId = ordersMapper.findByorderId(id);
        if (byorderId==null&& !byorderId.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        byorderId.setStatus(Orders.DELIVERY_IN_PROGRESS);
        ordersMapper.update(byorderId);
    }

    /**
     * 用户催单
     * @param id
     */
    @Override
    public void reminderid(Long id) {
        Orders byorderId = ordersMapper.findByorderId(id);
        if (byorderId==null){
            throw  new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        Map<String,Object> map=new HashMap<>();
        map.put("type",2);
        map.put("orderId",id);
        map.put("content","订单号"+byorderId.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    /**
     * 完成订单
     * @param id
     */
    @Override
    public void complete(Long id) {
        Orders byorderId = ordersMapper.findByorderId(id);
        if (byorderId==null&& !byorderId.getStatus().equals(Orders.COMPLETED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = new Orders();
        orders.setId(byorderId.getId());

        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());
        ordersMapper.update(orders);
    }
}